<?php
/*
 * [logging.php]
 * Console logging functions.
 *
 */

function report($how, $text) {
	// Figure out how wide the terminal is, or assume it is 80 columns wide.
	$term_width = `tput cols`;
	if (intval($term_width) == 0) $term_width = 80;
	$text_width = $term_width - 9;
	// Put a small indicator if no indicator was given, otherwise pad the indicator.
	if ($how == "") {
		$how = "       >";
	} else {
		$how = str_pad($how, 6, " ", STR_PAD_LEFT);
	}

	// Recursivly go through all line of the text.
	$lines = explode("\n", $text);
	$c = " ";
	$i = 0;
	foreach ($lines as $line) {
		// Check if the line was too long.
		$len = strlen($line);
		if ($len <= $text_width) {
			// Prepend the indicator.
			if ($i > 0) $c = "~"; // If this is the second (or more) line, use the marker.
			print "$how $c $line\n";
		} else {
			// The line was too long, we can’t display it.
			// Figure out how many parts the string has.
			$parts = $len / $text_width;
			// Fill an array with the smaller, split strings.
			$strings = Array();
			for ($j = 0; $j < $parts; $j++) {
				$strings[$j] = substr($line, $j * $text_width, $text_width);
			}
			// Display all the strings.
			foreach ($strings as $string) {
				print "$how $c $string\n";
				$c = "~"; // If there’s another line, use the marker.
			}
		}
		$i++;
	}
}

function log_recv($text) {
	report("<<<", $text);
}

function log_send($text) {
	report(">>>", $text);
}

function log_info($text) {
	report(">!<", $text);
}

function log_error($text) {
	report("<!>", $text);
}

function log_fatal($text) {
	report("!!!", $text);
	die("Fatal Error");
}

function log_debug($text) {
	global $config;
	if ($config["debug"]) report(">-<", $text);
}

?>
